<template>
  <el-form
    ref="form-ref"
    :rules="isNotOrder?headRules:{}"
    :model="headForm"
    :label-position="showMobilePage?'left':'right'"
    :class="{'mb-0 dividing':!isNotOrder}"
    label-width="100px"
    class="lineHeight32"
  >
    <el-row type="flex" class="response-el-row">
      <el-col :span="12" class="responsive-col-lg-8">
        <el-form-item :prop="'supplierSource'" label="供应商来源" >
          <selectWithoutHttp
            v-if="isNotOrder"
            v-model="headForm.supplierSource"
            :list-data="supplierSourceOption"
            class="width240"
            placeholder="请选择"
            key-name="id"
            label-name="value"
            @change="supplierSourceChange"
          />
          <div v-else>{{ headForm.supplierSource | supplierSourceFilter }}</div>
        </el-form-item>
      </el-col>
      <el-col :span="12" class="responsive-col-lg-8">
        <el-form-item :prop="'channelId'" label="供应商名称" >
          <SelectWithUserLoad
            v-if="resetPageFrom && isNotOrder"
            v-model="headForm.channelId"
            :loadmore-method="getSupplier()"
            :hide-select-list="headForm.channelId && headForm.channelName?[{id: headForm.channelId, supplier: headForm.channelName, supplierName: headForm.channelName}]:[]"
            :collapse-tags="false"
            :label-name="headForm.supplierSource===6?'supplierName':'supplier'"
            open-tool-tip
            key-name="id"
            filterable
            add-new
            class="width240"
            add-new-str="添加新供应商"
            @change="supplierChange"
            @changeMethod="supplierChangeMethod"
            @addNewClick="toCreateSupplier"
          />
          <div v-else-if="resetPageFrom">{{ headForm.channelName || '--' }}</div>
        </el-form-item>
      </el-col>
      <el-col v-if="!isNotOrder" :span="12" class="responsive-col-lg-8">
        <el-form-item prop="costBelong" label="成本来源" >
          <span class="content">{{ `${supplierCostBelong(costBelong)}${isInvite ? '(协作)' : ''}` }}</span>
        </el-form-item>
      </el-col>
      <el-col :span="12" class="responsive-col-lg-8">
        <el-form-item prop="settlementMethod" label="结算方式" >
          <div v-if="isNotOrder" class="flex-center">
            <selectWithoutHttp
              v-model="stepOneData.settlementMethod"
              :list-data="settlementMethodOption"
              :disabled="isEdit && !isDraft"
              class="width240"
              placeholder="请选择"
              key-name="id"
              label-name="value"
            />
            <tipIcon :content="settleMethodTip" :img-height="16" :img-width="16" max-width="350px" use-html class="ml8"/>
          </div>
          <span v-else class="content">{{ stepOneData.settlementMethod | settlementMethodFilter }}</span>
        </el-form-item>
      </el-col>
      <el-col v-if="!isNotOrder" :span="12" class="responsive-col-lg-8">
        <el-form-item prop="isInvite" label="协作方式" >
          <span class="content">{{ isInvite?'协作':'非协作' }}</span>
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>
</template>

<script>
import SelectWithUserLoad from '@/components/Common/selectWithUserLoad';
import selectWithoutHttp from '@/components/Common/selectWithoutHttp';
import { supplierManageList } from '@/api/supplier';
import { getMengliSuppliers } from '@/api/mengli';
import { getSupplierList } from '@/api/commerce';
import { mapState } from 'vuex';
import { hasRouteAuth } from '@/utils/permission';
// filters
import { supplierCostBelong } from '@/filters/status';

export default {
  filters: {
    supplierSourceFilter(num) {
      if (!num && num !== 0) return '--';
      if ([0, 1, 5].includes(num)) return '飞博供应商';
      if ([2, 3, 4].includes(num)) return '萌力供应商';
      if ([6].includes(num)) return '有赞供应商';
      return '--';

      // const map = {
      //   0: '飞博供应商',
      //   2: '萌力供应商',
      //   6: '有赞供应商'
      // };
      // return map[num] || '--';
    },
    settlementMethodFilter(num) {
      if (num === 0) {
        return '多次结算';
      } else if (num === 1) {
        return '一次结算';
      }
      return '--';
    }
  },
  components: { SelectWithUserLoad, selectWithoutHttp },
  model: {
    prop: 'headForm',
    event: 'changeData'
  },
  props: {
    headForm: {
      type: Object,
      default: () => ({})
    },
    isNotOrder: {
      type: Boolean,
      default: false
    },
    isInvite: {
      type: Boolean,
      default: false
    },
    stepOneData: {
      type: Object,
      default: () => ({})
    },
    costBelong: { // 成本归属 0:销售成本 2:萌力成本 6:有赞成本
      type: Number,
      default: 0
    },
    isEdit: {
      type: Boolean,
      default: false
    },
    isDraft: {
      type: Boolean,
      default: false
    }
  },
  data() {
    const validateSelect = (msg) => {
      return (ruleItem, value, callback) => {
        const channel = this.headForm.channelId;
        if (!channel) { callback(new Error(msg)); } else { callback(); }
      };
    };
    const validateSettlementMethod = () => {
      return (ruleItem, value, callback) => {
        const settlementMethod = this.stepOneData.settlementMethod;
        if (!settlementMethod && settlementMethod !== 0) {
          callback(new Error('请选择结算方式'));
        } else { callback(); }
      };
    };
    return {
      headRules: {
        channelId: { required: true, validator: validateSelect('请选择供应商'), trigger: 'change' },
        settlementMethod: { required: true, validator: validateSettlementMethod(), trigger: 'change' }
      },
      resetPageFrom: true,
      supplierSourceOption: [{ id: 0, value: '飞博供应商' }, { id: 2, value: '萌力供应商' }, { id: 6, value: '有赞供应商' }],
      settlementMethodOption: [{ id: 1, value: '一次结算' }, { id: 0, value: '多次结算' }]
    };
  },
  computed: {
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage
    }),
    settleMethodTip() {
      return `<div class="mb5">一次结算：仅进行一次审批，实付金额必须等于订单结算总金额</div><div>多次结算：可发起多次审批，多次审批单的实付金额之和必须等于订单结算总金额</div>`;
    }
  },
  watch: {
    'headForm.supplierSource': {
      handler(val) {
        this.resetPageFrom = false;
        this.$nextTick(() => {
          this.resetPageFrom = true;
        });
      },
      deep: true
    }
  },
  methods: {
    supplierCostBelong,
    hasRouteAuth,
    changeData() {
      this.$emit('changeData', this.headForm);
    },
    validate() {
      return this.$refs['form-ref'].validate();
    },
    clearValidate() {
      this.$nextTick(() => {
        this.$refs['form-ref'].clearValidate();
      });
    },
    getSupplier() {
      // 【供应商来源  0:销售供应商  2:萌力供应商 6：有赞供应商
      const supplierSource = this.headForm.supplierSource;
      const a = function(params) {
        return new Promise((resolve, reject) => {
          params.supplier = '';
          params.keyword = '';
          if (params.userName) {
            if (supplierSource === 0) {
              params.supplier = params.userName;
            } else {
              params.keyword = params.userName;
            }
          }
          const getFunObj = {
            0: supplierManageList,
            2: getMengliSuppliers,
            6: getSupplierList
          };
          const getFun = getFunObj[supplierSource];
          getFun(params).then(res => {
            resolve(res);
          }).catch(err => {
            reject(err);
          });
        });
      };
      return a;
    },
    supplierSourceChange() {
      this.$set(this.headForm, 'channelId', '');
      this.$set(this.headForm, 'channelName', '');
      this.changeData();
    },
    supplierChange() {
      this.changeData();
    },
    supplierChangeMethod(data) {
      this.$emit('supplierChangeMethod', data);
    },
    toCreateSupplier() {
      const { supplierSource } = this.headForm;
      let name = 'supplierManage';
      if ([2, 3, 4].includes(supplierSource)) {
        if (!this.hasRouteAuth('mengli:supplier:create')) {
          this.$message.error('暂无供应商新建权限！');
          return;
        }
        name = 'mengliCreateSupplier';
      }
      if ([6].includes(supplierSource)) {
        if (!this.hasRouteAuth('crm:commerceSupplier:add')) {
          this.$message.error('暂无供应商新建权限！');
          return;
        }
        name = 'commerceSupplierCreate';
      }
      const query = { name };
      if ([0, 1, 5].includes(supplierSource)) {
        query.query = { toCreate: 1 };
        if (!this.hasRouteAuth('medium:supplier:edit')) {
          this.$message.error('暂无供应商新建权限！');
          return;
        }
      }
      const routeUrl = this.$router.resolve(query);
      window.open(routeUrl.href, '_blank');
    }
  }
};
</script>

<style lang="scss" scoped>
.mb-0 {
  margin-bottom: 20px;
  &::v-deep {
    .el-form-item {
      margin-bottom: 0;
    }
  }
}
.width240 {
  width: 240px;
  & ::v-deep {
    .el-input__inner {
      width: 240px;
    }
  }
}
.dividing{

  &::v-deep {
    .el-form-item__label {
      color: #999;
      &::after {
        content: ':';
      }
    }
  }
  @media only screen and (min-width: 1300px) {
    &::v-deep {
      .el-col {
        &:nth-child(3n) {
          .el-form-item__content {
            border-right: none;
          }
        }
        .el-form-item__content {
          border-right: 1px solid #EBEEFD;
        }
        &:last-child {
          .el-form-item__content {
            border-right: none;
          }
        }
      }
    }
  }
}
</style>
